import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:orginone/components/EmptyWidget/EmptyWidget.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/thing/standard/application.dart';
import 'package:orginone/dart/core/work/index.dart';
import 'package:orginone/main.dart';
import 'package:orginone/pages/portal/assets_management/assets_module/asset_type.dart';
import '../../../components/EntityWidget/EntitySwitchWidget/model.dart';
import '../../../components/PortalManagerWidget/portalrefresh_event.dart';

class AppManagementPage extends StatefulWidget {
  Application xappdata;
  AppManagementPage({Key? key, required this.xappdata}) : super(key: key);

  @override
  State<AppManagementPage> createState() => _AppManagementPageState();
}

class _AppManagementPageState extends State<AppManagementPage> {


  IApplication? app;

  @override
  Widget build(BuildContext context) {
    return (null == widget.xappdata) ? EmptyWidget() : buildType(widget.xappdata);
    // return FutureBuilder(
    //   future: expensiveOperation(), // 你的耗时操作
    //   builder: (context, snapshot) {
    //     if (snapshot.connectionState == ConnectionState.done) {
    //       return (null == app) ? EmptyWidget() : buildType(app!);
    //     }
    //     return const Center(
    //       child: CircularProgressIndicator(),
    //     );// 加载指示器
    //   },
    // );
    // return EntitySwitchWidget<IApplication>(
    //     data: ApplicationData("应用"),
    //     buildChildren: (IApplication app) {
    //       return Future(() async {
    //         return buildType(app);
    //       });
    //     });
    // return SingleChildScrollView(
    //   child: Column(
    //     children: [buildSelectApp(), Obx(() => buildType())],
    //   ),
    // );
  }

  // 耗时操作
  Future<String> expensiveOperation() async {
    app = await relationCtrl.findApplicationById(widget.xappdata.id);
    return '完成';
  }


  Widget buildType(Application app) {
    Widget content;
    if (app!.children.isEmpty) {
      content = FutureBuilder(
          future: app.loadWorks(),
          builder: (BuildContext context, AsyncSnapshot<List<IWork>> shot) {
            if (shot.hasData && shot.connectionState == ConnectionState.done) {
              return SingleChildScrollView(
                  child: buildItemApp(context, shot.data ?? []));
            }
            return /*const CircularProgressIndicator()*/Container();
          });
    } else {
      content = Column(
          children:
              app.children.map((e) => AssetsTypePage(typeData: e)).toList());
    }
    return Container(
      color: Colors.white,
      child: SingleChildScrollView(
        child: content,
      ),
    );
  }

//   buildSelectApp() {
//     return Obx(() => assetLogic.currentIndex < 0
//         ? Container()
//         : Container(
//             padding: const EdgeInsets.all(16),
//             width: UIConfig.screenWidth,
//             decoration: const BoxDecoration(
//               border: Border(
//                 bottom: BorderSide(
//                   width: 1.0, // 边框的宽度
//                   color: XColors.dividerLineColor, // 边框的颜色
//                 ),
//               ),
//             ),
//             child: Row(
//               children: [
//                 Expanded(
//                   child: SingleChildScrollView(
//                     scrollDirection: Axis.horizontal,
//                     child: Row(
//                       children: [
//                         Text(
//                             assetLogic.applications.isNotEmpty
//                                 ? assetLogic
//                                     .applications[assetLogic.currentIndex.value]
//                                     .name
//                                 : '',
//                             style: XFonts.size24Black0W700),
//                         if (assetLogic.applications.isNotEmpty &&
//                             assetLogic
//                                 .applications[assetLogic.currentIndex.value]
//                                 .groupTags
//                                 .isNotEmpty)
//                           Container(
//                               margin: const EdgeInsets.only(left: 8),
//                               padding: const EdgeInsets.fromLTRB(2, 6, 2, 6),
//                               decoration: const BoxDecoration(
//                                   color: Color(0xfff2f3ff),
//                                   borderRadius:
//                                       BorderRadius.all(Radius.circular(3))),
//                               child: Text(
//                                   assetLogic
//                                       .applications[
//                                           assetLogic.currentIndex.value]
//                                       .groupTags[0],
//                                   overflow: TextOverflow.ellipsis,
//                                   maxLines: 1,
//                                   style: TextStyle(
//                                       fontSize: 14.sp,
//                                       color: XColors.themeColor)))
//                       ],
//                     ),
//                   ),
//                 ),
//                 const SizedBox(width: 4),
//                 GestureDetector(
//                   onTap: () {
//                     showSearchApplication(navigatorKey.currentState!.context, assetLogic.applications,
//                         title: "选择应用",
//                         hint: "搜索", onSelected: (application) async {
//                       assetLogic.currentIndex.value =
//                           assetLogic.applications.indexOf(application[0]);
//                       assetLogic.loadWorks();
//                       await relationCtrl.user!.cacheObj
//                           .set('assetmodule', application[0].metadata);
//                     });
//                   },
//                   child: Row(
//                     children: [
//                       Text('切换应用', style: XFonts.size22Black0),
//                       const Icon(
//                         Icons.arrow_forward_ios,
//                         size: 18,
//                       )
//                     ],
//                   ),
//                 )
//               ],
//             )));
//   }
}

class ApplicationData extends EntitySwitchModel<IApplication> {
  // List<IWork> allIworkWithNoType = [];

  ApplicationData(super.title);

  @override
  Future<IApplication?> getInitData() async {
    IApplication? res;
    XApplication? cacheApp = await relationCtrl.user!.cacheObj
        .get<XApplication>('assetmodule', XApplication.fromJson);
    if (cacheApp != null) {
      res = datas.firstWhereOrNull((element) => element.id == cacheApp.id);
      // currentIndex.value = datas.indexOf(res);
      // loadWorks(res);
    }
    res ??= datas.firstOrNull;
    return res;
  }

  @override
  Future<List<IApplication>> getInitDatas() async {
    List<IApplication> app = await relationCtrl.loadApplications();
    return app
        .where((element) =>
            // element.name == "资产管理" &&
            !element.groupTags.contains("已删除") &&
            element.directory.target.typeName != DirectoryType.storage.label)
        .toSet()
        .toList();
  }

  @override
  void setCurrData(IApplication? currData) async {
    if (null != currData) {
      XApplication? cacheApp = await relationCtrl.user!.cacheObj
          .get<XApplication>('assetmodule', XApplication.fromJson);
      var navigationItems =
          relationCtrl.user!.cacheObj.getValue("portalTemplate");
      if (null != navigationItems && navigationItems.isNotEmpty) {
        navigationItems.forEach((value) {
          if (value['name'] == cacheApp!.name) {
            value['belongId'] = currData.belongId;
            value['name'] = currData.metadata.name;
            value['tags'] = ['应用模板', currData.directory.metadata.name];
            value['id'] = '${currData.belongId}_${currData.metadata.id}';
            value['metadata'] = currData.metadata;
            value['key'] =
                'home_Module${currData.metadata.belongId}_${currData.metadata.id}';
          }
        });
        relationCtrl.user!.cacheObj.set("portalTemplate", navigationItems);
        relationCtrl.user!.cacheObj.set('assetmodule', currData.metadata);
        portalRefreshEventBus.fire(PortalRefreshEvent(-1));
      }
    }
  }

  // Future<void> loadWorks(IApplication? app) async {
  //   allIworkWithNoType = await app?.loadWorks() ?? [];
  // }
}
